import React from 'react'
//import reactdom from 'react-router-dom'
import {Table,Tag,Button,message,Input,Form,Select,Upload,Modal} from 'antd'
import moment from 'moment'
import api from '../../until/index.js'
import {  PlusOutlined } from '@ant-design/icons'
function getBase64(file) {
    console.log(file,'base64')
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}
export default class User extends React.Component{
    formRef = React.createRef()
    constructor(){
        super()
        this.state={
            colums:[{title:'#',align:'center',dataIndex:'id',key:'id',render:(text,record,index)=>`${index+1}`},
        {title:'用户名称',width:150, align:'center',dataIndex:'user',key:'user'},
        { title: '会员头像', align: 'center', dataIndex: 'img', key: 'img', render: (text) => <img alt="" key="img" style={{ width: '60px', height: '60px' }} src={text} /> },
        {title:'密码',align:'center',dataIndex:'password',key:'password'},
        {title:'性别',align:'center',dataIndex:'gender',key:'gender',render: (text) => text == '1' ? <Tag color="green">男生</Tag> : <Tag color="red">女性</Tag> //eslint-disable-line 
    },{title:'积分',dataIndex:'inte',key:'inte',align:'center'},{title:'余额',dataIndex:'money',key:'money',align:'center'},
    {title:'创建时间',dataIndex:'time',key:'time',render:val=><span>{val?moment(val).format('YYYY-MM-DD HH:mm:ss'):moment('2020-6-1 00:00:00').format('YYYY-MM-DD HH:mm:ss')}</span>},
{title:'操作',align:'center',render:(text)=><div 
style={{width:'100%',display:'flex',justifyContent:'space-between'}}><Button onClick={()=>this.getuserUpdate(text.id)} size="small" type="primary">编辑</Button>
<Button size="small" danger onClick={this.userdetail}>删除</Button></div>}],
    dataList:[],
    previewVisible: false,
    previewImage: '',
    previewTitle: '',
    fileList:[],
    Flag:false,
    id:'',
    user:'',
    password:'',
    psd:'',
    gender:'',
    img:''
        }
    }
    componentDidMount(){
        api.getuserlist().then(res=>{
            this.setState({
                dataList:res.data.message.reverse()
            })
        })
    }
    //修改
    getuserUpdate=(text)=>{
        api.getuserlist({id:text}).then(res=>{
            
            this.setState({
                user:res.data.message[0].user,
                gender:res.data.message[0].gender,
                fileList:[{uid:1,url:res.data.message[0].img||'',status:'success',name:'image.png'}],
                password:''
            })
            if(this.formRef.current){
                this.formRef.current.setFieldsValue({
                    user:res.data.message[0].user,
                    gender:res.data.message[0].gender,
                    password:''
                })
            }
        })
        this.setState({
            Flag:!this.state.Flag,
            id:text
        })
    }
    //确定修改
    handleOk=()=>{
        let img=''
        this.state.fileList.forEach(item=>{
            if(item.response){
                img=item.response.data
            }else{
                img=item.url
            }
        })
        this.formRef.current.validateFields().then(res=>{
            let data={
                id:this.state.id,
                user:this.state.user,
                gender:this.state.gender,
                img:img,
                time:new Date()
            }
            api.getuserupdate(data).then(result=>{
                if(result.data.err_code==0){ //eslint-disable-line
                    message.success('修改成功')
                    this.setState({
                        Flag:!this.state.Flag
                    })
                    this.componentDidMount()
                }
            })
        })
    }
    //关闭修改
    handleCancel = () => {
        this.setState({
            Flag: !this.state.Flag
        })
    }
    //输入框监听
    onChange = (e) => {
        console.log(e)
        this.setState({
            [e.target.name]: e.target.value
        })

    }
    //删除
    userdetail=(text)=>{
        message.warning('抱歉您没有权限')
    }
     //图片预览
     handlePreview = async file => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }

        this.setState({
            previewImage: file.url || file.preview,
            previewVisible: true,
            previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
        });
    }
    //头像上传
    handleChangeImage=({fileList})=>{
        this.setState({fileList})
    }
    //性别选择
    handleChanges = (text) => {
        this.setState({
            gender: text
        })
    }
    //校验密码
    onBlur=()=>{
        api.getpassword({id:this.state.id,password:this.state.password}).then(res=>{
            if(res.data.err_code==400){ //eslint-disable-line
                message.warning('请输入正确的旧密码')
            }
        })
    }
    render(){
        const {colums,dataList,user,fileList,previewVisible,previewTitle,previewImage}=this.state
        const opt=[{value:'0',label:'女生'},{value:'1',label:'男生'}]
        const uploadButton = (
            <div>
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>上传头像</div>
            </div>
        )
        return(
            <div>
                <Table columns={colums} dataSource={dataList} bordered bottomLeft rowKey={record => record.id}></Table>
                <Modal title="修改会员信息" width={1000} visible={this.state.Flag} onOk={this.handleOk} onCancel={this.handleCancel} footer={null} destroyOnClose={true}>
                    <Form onFinish={this.onFinish}   labelCol={{ span: 4 }} ref={this.formRef}
                        wrapperCol={{ span: 14 }}>
                        <Form.Item rules={[{ required: true, message: '请输入用户名' }]} name="user" label="用户名称">
                            <Input onChange={this.onChange} value={user} allowClear></Input>
                        </Form.Item>
                        <Form.Item  name="password" label="旧密码">
                            <Input type="password" name="password" onBlur={this.onBlur} onChange={this.onChange} ></Input>
                        </Form.Item>
                        <Form.Item  name="psd" label="新密码">
                            <Input type="password" name="psd" onChange={this.onChange} ></Input>
                        </Form.Item>
                        <Form.Item rules={[{ required: true, message: '请选择性别' }]} name="gender" label="适用人群">
                            <Select options={opt} onChange={this.handleChanges} name="gender"></Select>
                        </Form.Item>
                       
                        <Form.Item rules={[{ required: false, message: '请上传用户头像' }]} name="url" label="用户头像">
                           <div>
                           <Upload action="https://dbyxs.xyz:8002/img" listType="picture-card" fileList={fileList} onPreview={this.handlePreview} onChange={this.handleChangeImage}>
                                {fileList.length >= 1 ? null : uploadButton}
                            </Upload>
                            <Modal visible={previewVisible} title={previewTitle} footer={null} onCancel={this.handleCancelPer}>
                                <img alt="example" style={{ width: '100%' }} src={previewImage} />
                            </Modal>
                           </div>
                        </Form.Item>
                        
                    </Form>
                    <div style={{ textAlign: "center" }}>
                        <Button onClick={this.handleOk} htmlType="submit" type="primary">提交</Button>
                        <Button onClick={this.handleCancel} danger style={{ marginLeft: 30 }}>删除</Button>
                    </div>

                </Modal>
            </div>
        )
    }
}
 